<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:set var="reportTitle" value="SPC Chart图报表" />

<%@ include file="/common/report_head.jsp" %>
<%@ include file="/condition/sartTime_input.html"%>
<%@ include file="/condition/endTime_input.html"%>
<%@ include file="/condition/fab_sumo_must.html"%>
<%@ include file="/condition/line_sumo.html"%>
<%@ include file="/condition/ope_sumo.html"%>
<%@ include file="/condition/tool_main_sumo.html"%>
<%@ include file="/condition/tool_sub_sumo.html"%>
<%@ include file="/condition/boatNumber_sumo.html"%>
<%--<%@ include file="/condition/shift_sumo.html"%>--%>
<%@ include file="/condition/controlChartGrp_sumo.html"%>
<%@ include file="/condition/controlChart_sumo.html"%>
<%@ include file="/condition/showHidePoint_radio.html"%>

<%@ include file="/common/report_middle.jsp" %>
<%@ include file="/charts-grid/echarts2.html"%>
<%@include file="/common/report_end.jsp" %>


<script>
    $(document).ready(function () {
        $("title").text("SPC Chart图报表");
        var global_data; //定义全局数据;

        $("label:contains('管制图组:')").addClass("keyCss");
        $("label:contains('管制图:')").addClass("keyCss");

        $('#query_btn').click(function (){
            if($("#controlChartGrpSumo").val() === null || $("#controlChartGrpSumo").val() === '' || $("#controlChartSumo").val() === null || $("#controlChartSumo").val() === ''){
                showErrorDialog("0000002", "管制图组和管制图为必选项"); return false;
            }
            initGridAndChart();
            global_data = null;
            ajax('/jn-report/report/spc_chart_report.do' ,loadConditionMapData(), true, ajax_successful);

            function ajax_successful(outTrxObj) {
                if(outTrxObj.chartsData.length < 1) { showMessengerDialog("数据查询为空"); return false; }

                //Chart图数据赋值
                if ($("#charts").length > 0) {
                    var echartsData = outTrxObj.chartsData;
                    option.backgroundColor = 'white';
                    option.grid.show = false;
                    option.title.text = echartsData.title;
                    option.legend.data = [];
                    option.legend.data = echartsData.legendData;
                    option.xAxis[0].data = [];
                    option.xAxis[0].data = echartsData.xAxisData;
                    option.series = [];
                    for (var i = 0; i < echartsData.series2Datas.length; i++) {
                        option.series.push({
                            name: echartsData.legendData[i],
                            type: 'line',
                            data: echartsData.series2Datas[i],
                            symbol: 'circle',
                            symbolSize: 6
                        });
                    }
                    //控制线/规格线/中心线的设置
                    if (outTrxObj.mainChartSetting.hasOwnProperty("chart_usl")){
                        option.series.push({
                            type: 'line',
                            markLine: {
                                silent: true,//不响应鼠标事件
                                itemStyle: {
                                    normal: { lineStyle: { type: 'solid', color:'red' },label: { position:'end', formatter: 'USL' } }
                                },
                                data: [{yAxis:outTrxObj.mainChartSetting.chart_usl}, {yAxis:outTrxObj.mainChartSetting.chart_usl}]
                            }
                        });
                    }
                    if (outTrxObj.mainChartSetting.hasOwnProperty("chart_ucl")){
                        option.series.push({
                            type: 'line',
                            markLine: {
                                silent: true,//不响应鼠标事件
                                itemStyle: {
                                    normal: { lineStyle: { color:'red' },label: { position:'end', formatter: 'UCL' } }
                                },
                                data: [{yAxis: outTrxObj.mainChartSetting.chart_ucl}, {yAxis: outTrxObj.mainChartSetting.chart_ucl}]
                            }
                        });
                    }
                    if (outTrxObj.mainChartSetting.hasOwnProperty("chart_target")){
                        option.series.push({
                            type: 'line',
                            markLine: {
                                silent: true,//不响应鼠标事件
                                itemStyle: {
                                    normal: { lineStyle: { type: 'solid', color:'blue' },label: { position:'end', formatter: 'Target' } }
                                },
                                data: [{yAxis: outTrxObj.mainChartSetting.chart_target}, {yAxis: outTrxObj.mainChartSetting.chart_target}]
                            }
                        });
                    }
                    if (outTrxObj.mainChartSetting.hasOwnProperty("chart_lcl")){
                        option.series.push({
                            type: 'line',
                            markLine: {
                                silent: true,//不响应鼠标事件
                                itemStyle: {
                                    normal: { lineStyle: { color:'red' },label: { position:'end', formatter: 'LCL' } }
                                },
                                data: [{yAxis: outTrxObj.mainChartSetting.chart_lcl}, {yAxis: outTrxObj.mainChartSetting.chart_lcl}]
                            }
                        });
                    }
                    if (outTrxObj.mainChartSetting.hasOwnProperty("chart_lsl")){
                        option.series.push({
                            type: 'line',
                            markLine: {
                                silent: true,//不响应鼠标事件
                                itemStyle: {
                                    normal: { lineStyle: { type: 'solid', color:'red' },label: { position:'end', formatter: 'LSL' } }
                                },
                                data: [{yAxis: outTrxObj.mainChartSetting.chart_lsl}, {yAxis: outTrxObj.mainChartSetting.chart_lsl}]
                            }
                        });
                    }
                    //最大/最小显示范围的设置
                    //option.yAxis[0].max = outTrxObj.mainChartSetting.chart_usl;
                    //option.yAxis[0].min = outTrxObj.mainChartSetting.chart_lsl;
                    option.yAxis[0].max = echartsData.maxValue;
                    option.yAxis[0].min = echartsData.minValue;
                    option.tooltip = {
                        trigger: 'axis',
                        formatter: function (params) {
                            var res;
                            res = '上报时间:' + params[0].data[0] + '<br/>';
                            res += '点值:' + params[0].data[1] + '<br/>';
                            res += '上报人:' + params[0].data[2] + '<br/>';
                            res += '设备代码:' + params[0].data[3] + '<br/>';
                            res += '上控制线:' + params[0].data[4] + '<br/>';
                            res += '下控制线:' + params[0].data[5] + '<br/>';
                            return res;
                        }
                    }
                    myChart.clear();
                    myChart.setOption(option);
                }

                global_data = outTrxObj; //全局数据赋值
                loadGridData(outTrxObj); //表格数据赋值
                chartLegendChangeEvent();//Chart图-Legend Change事件
                //chartPointClickEvent();  //Chart图-点 点击事件
            }
        });


        // Chart图点点击事件
        chartPointClickEvent();
        function chartPointClickEvent() {
            myChart.on('click', function (params) {
                var pdata = params.data;
                var data = {
                    processEqptId       : pdata[0],
                    value               : pdata[1],
                    chart_value         : pdata[1],
                    evt_usr             : pdata[2],
                    reporter            : pdata[2],
                    m_tool_id_fk        : pdata[3],
                    ucl                 : pdata[4],
                    chart_ucl_fk        : pdata[4],
                    lcl                 : pdata[5],
                    chart_lcl_fk        : pdata[5],
                    chart_rule_1_rlt_fk : pdata[6],
                    comment             : pdata[7],
                    processEqptId       : pdata[8],
                    col_typ_fk          : pdata[9],
                    grp_no_fk           : pdata[10],
                    chart_no_fk         : pdata[11],
                    chart_typ_fk        : pdata[12],
                    input_time_d        : pdata[13],
                    inputTimestamp      : pdata[14],
                    chart_usl_fk        : pdata[15],
                    chart_lsl_fk        : pdata[16],
                    index               : pdata[22]
                };
                showChartComment(data);
            });
        }

        // 隐藏点值
        var message;
        var index;
        var cache_map = {};
        function showChartComment(data) {
            var chartRuleRlt = data.chart_rule_1_rlt_fk;
            var comment = data.comment ? data.comment : "";

            var str = '<div id = "pointInfoModal" class="modal fade">';
            str += '<div class="modal-dialog">';
            str += '<div class="modal-content">';
            str += '<div class="modal-header">';
            str += '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>';
            str += '</div>';
            str += '<div class="modal-body">';
            str += "<table class='table table-striped'><caption>详细信息</caption>";
		    //str += "<thead><tr><th>项目</th><th>值</th></tr></thead>"
            str += "<tr><td>序列</td><td>" + data.index + "</td>";
            str += "<tbody><tr><td>上报时间</td><td>" + data.inputTimestamp + "</td></tr>";
            str += "<tr><td>上报人</td><td>" + data.reporter + "</td></tr>";
            //str += "<tr><td>玻璃代码</td><td>" + data.glass_id + "</td></tr>";
            str += "<tr><td>制程机台</td><td>" + data.processEqptId + "</td></tr>";
            str += "<tr><td>数据点值</td><td>" + data.chart_value + "</td></tr>";
            if (typeof(data.ucl) !== "undefined" && typeof(data.lcl) !== "undefined") {
                str += "<tr><td>上控制线</td><td>" + Number(data.ucl).toFixed(2) + "</td></tr>";
                str += "<tr><td>下控制线</td><td>" + Number(data.lcl).toFixed(2) + "</td></tr>";
            }

            if (cache_map[data.index] != "" && cache_map[data.index] != undefined) {
                comment = cache_map[data.index];
            }

            str += "<tr><td>备注</td><td><input id='commentTxt' type='text' value= '" + comment + "' /> <button id='addCommentBtn' class='btn btn-info' >添加备注</button></td></tr>"
            str += "<tr><td>隐藏</td><td><button id='hideBtn' class='btn btn-warning' >隐藏该点</button></td></tr>"
            /*str += "<tr><td>删除按钮</td><td><button id='deleteBtn' class='btn btn-danger' >删除该数据</button></td></tr>"*/
            str += "<tr style='display:none'><td>col_typ_fk</td><td id='colTypTd'>" + data.col_typ_fk + "</td></tr>"
            str += "<tr style='display:none'><td>grp_no_fk</td><td id='grpNoTd'>" + data.grp_no_fk + "</td></tr>"
            str += "<tr style='display:none'><td>chart_no_fk</td><td id='chartNoTd'>" + data.chart_no_fk + "</td></tr>"
            str += "<tr style='display:none'><td>chart_typ_fk</td><td id='chartTypTd'>" + data.chart_typ_fk + "</td></tr>"
            str += "<tr style='display:none'><td>input_time_d</td><td id='inputTimeDTd'>" + data.input_time_d + "</td></tr>"


            if (chartRuleRlt) {
                var chartRule1 = chartRuleRlt[0];
                if (chartRule1 && chartRule1 === "Y") {
                    str += "<tr><td>超规</td><td>一点跳出管界限外</td></tr>";
                }
                var chartRule2 = chartRuleRlt[1];
                if (chartRule2 && chartRule2 === "Y") {
                    str += "<tr><td>超规</td><td color='red'>连续八点落在中心线同一侧</td></tr>";
                }
                var chartRule3 = chartRuleRlt[2];
                if (chartRule3 && chartRule3 === "Y") {
                    str += "<tr><td>超规</td><td color='red'>连续六点上升或下降</td></tr>";
                }
                var chartRule4 = chartRuleRlt[3];
                if (chartRule4 && chartRule4 === "Y") {
                    str += "<tr><td>超规</td><td color='red'>连续十四点交互着上下跳动</td></tr>";
                }
                var chartRule5 = chartRuleRlt[4];
                if (chartRule5 && chartRule5 === "Y") {
                    str += "<tr><td>超规</td><td color='red'>连续三点有两点落在2σ以外</td></tr>";
                }
                var chartRule6 = chartRuleRlt[5];
                if (chartRule6 && chartRule6 === "Y") {
                    str += "<tr><td>超规</td><td color='red'>连续五点中有四点落在1σ外</td></tr>";
                }
                var chartRule7 = chartRuleRlt[6];
                if (chartRule7 && chartRule7 === "Y") {
                    str += "<tr><td>超规</td><td color='red'>连续十五点在中心线上下两侧1σ以内</td></tr>";
                }

            }
            str += "</tbody></table>";
            str += '</div>';
            str += '<div class="modal-footer">';
            //str +='<a href="#" class="btn">关闭</a>';
            //str +=' <a href="#" class="btn btn-primary">Save changes</a>';
            str += '</div>';
            str += '</div>';
            str += '</div>';
            str += '</div>';
            if ($("#pointInfoModal").length > 0) {
                $("#pointInfoModal").remove();
            }
            $(str).appendTo("main");

            $("#pointInfoModal").modal({keyboard: true});
            $("#pointInfoModal").modal("show");

            /**  暂不支持删除点功能 ***/
            //$("#deleteBtn").unbind("click");
            //$("#deleteBtn").bind("click", function () {
            //    var colTyp = $("#colTypTd").text(),
            //        grpNo = $("#grpNoTd").text(),
            //        chartNo = $("#chartNoTd").text(),
            //        chartTyp = $("#chartTypTd").text(),
            //        inputTimeD = $("#inputTimeDTd").text();
            //
            //    var inTrxObj = {
            //        trx_id: "XPCCHTDT",
            //        action_flg: "d",
            //        col_typ: colTyp,
            //        grp_no: grpNo,
            //        chart_no: chartNo,
            //        chart_typ: chartTyp,
            //        input_time_d: inputTimeD,
            //        evt_usr:VAL.EVT_USR
            //    };
            //    var outTrxObj = comTrxSubSendPostJson(inTrxObj);
            //    if (outTrxObj.rtn_code == "0000000") {
            //        showSuccessDialog("成功删除该点数据！，请刷新页面");
            //        return true;
            //    }
            //    $('#pointInfoModal').modal("hide");
            //});

            $("#addCommentBtn").unbind("click");
            $("#addCommentBtn").bind("click", function () {
                var colTyp = $("#colTypTd").text(),
                    grpNo = $("#grpNoTd").text(),
                    chartNo = $("#chartNoTd").text(),
                    chartTyp = $("#chartTypTd").text(),
                    inputTimeD = $("#inputTimeDTd").text();
                    comment = $("#commentTxt").val();

                if (!comment) {
                    showErrorDialog("", "请输入要备注信息");
                    return false;
                }

                var inTrxObj = {
                    trx_id        : "XPSPCCHART",
                    action_flg    : "A",
                    col_typ_fk    : colTyp,
                    grp_no_fk     : grpNo,
                    chart_no_fk   : chartNo,
                    chart_typ_fk  : chartTyp,
                    input_time_d  : inputTimeD,
                    chart_comment : comment,
                    evt_usr       : $("#userSpan").text()
                };
                var outTrxObj = comTrxSubSendPostJson(inTrxObj);
                if (outTrxObj.rtn_code == "0000000") {
                    showSuccessDialog("添加备注成功");
                    message = comment;
                    index = data.index;
                    cache_map[index] = message;
                    // _this.activeChart.data.point[index].chart_comment = comment;
                }
                $('#pointInfoModal').modal("hide");

            });

            //todo 隐藏不需要的点
            $("#hideBtn").unbind("click");
            $("#hideBtn").bind("click", function () {
                var colTyp = $("#colTypTd").text(),
                    grpNo = $("#grpNoTd").text(),
                    chartNo = $("#chartNoTd").text(),
                    chartTyp = $("#chartTypTd").text(),
                    inputTimeD = $("#inputTimeDTd").text();

                var inTrxObj = {
                    trx_id        : "XPSPCCHART",
                    action_flg    : "H",
                    col_typ_fk    : colTyp,
                    grp_no_fk     : grpNo,
                    chart_no_fk   : chartNo,
                    chart_typ_fk  : chartTyp,
                    input_time_d  : inputTimeD,
                    evt_usr       : $("#userSpan").text()
                };
                var outTrxObj = comTrxSubSendPostJson(inTrxObj);
                if (outTrxObj.rtn_code == "0000000") {
                    showSuccessDialog("设置隐藏成功！");
                    index = data.index;
                    // _this.activeChart.data.point[index].chart_comment = comment;
                }
                $('#pointInfoModal').modal("hide");
            });
            return false;
        }

        // Chart图Legend改变事件
        function chartLegendChangeEvent() {
            myChart.on('legendselectchanged', function(obj) {
                console.info("legend select chang!");
                var change_chart_name = obj.name.split("   ")[0];

                //有管制图的设备
                var toolId_Array = [];
                for (var legend in obj.selected){
                    if (change_chart_name === legend.split("   ")[0] && obj.selected[legend] == true) {
                        toolId_Array.push(legend.split("   ")[1]);
                    }
                }
                //数据计算值改变
                for (var i=0; i<global_data.chartGridVo_list.length; i++){
                    var chartSetting = global_data.chartGridVo_list[i].chartSetting;
                    var pointDataList = global_data.chartGridVo_list[i].pointData;
                    if (chartSetting.chart_name === change_chart_name) {
                        var new_pointDateList = [];
                        for (var j=0; j<pointDataList.length; j++) {
                            if (toolId_Array.indexOf(pointDataList[j].tool_id) >= 0){
                                new_pointDateList.push(pointDataList[j]);
                            }
                        }
                        showGridData(i,chartSetting, new_pointDateList);
                    }
                }
                //汇总数据计算值改变
                var legend_Array = [];
                var summary_pointDateList = [];
                for (var legend in obj.selected){
                    if (obj.selected[legend] == true) {
                        legend_Array.push(legend);
                    }
                }
                for (var i=0; i<global_data.chartGridVo_list.length; i++){
                    var chartSetting = global_data.chartGridVo_list[i].chartSetting;
                    var pointDataList = global_data.chartGridVo_list[i].pointData;
                    for (var k=0; k<legend_Array.length; k++){
                        var chart_name = legend_Array[k].split("   ")[0];
                        var tool_name = legend_Array[k].split("   ")[1];
                        if (chartSetting.chart_name === chart_name) {
                            for (var j=0; j<pointDataList.length; j++) {
                                if (pointDataList[j].tool_id === tool_name){
                                    summary_pointDateList.push(pointDataList[j]);
                                }
                            }
                        }
                    }
                }
                global_data.mainChartSetting.chart_name = "汇总数据计算"
                showGridData("汇总数据计算", global_data.mainChartSetting, summary_pointDateList);
            });
        }

        function loadGridData(outTrxObj) {
            if ($("#gridDataDiv").length > 0){
                $("#gridDataDiv").remove();
            }
            $("main").append("<div id='gridDataDiv'></div>");

            function buildHtml(i, chartSetting, pointDataList) {
                var dataDiv_id = "dataDiv_" + i;
                var sumaryDataDiv_id = "sumaryDataDiv_" + i;
                var rawDataDiv_id = "rawDataDiv_" + i;
                var chartDataDiv_id = "chartDataDiv_" + i;
                var html = "<div id='" + dataDiv_id + "' class='col-md-11' style='margin-bottom: 35px;margin-left: 80px;border: 1px solid midnightblue;padding: 0;'>" +
                    "<p style='background-color: silver;font-size: 17px;font-weight: bold;text-indent: 2em;border-bottom: 1px solid black;'>" + chartSetting.chart_name + "</p>" +
                    "<div id='" + sumaryDataDiv_id + "' class='col-md-12' ></div>" +
                    "<div id='" + rawDataDiv_id + "' class='col-md-12'></div>" +
                    "<div id='" + chartDataDiv_id + "' class='col-md-12'></div>" +
                    "</div>"
                $("#gridDataDiv").append(html);
                showGridData(i, chartSetting, pointDataList);
            }
            outTrxObj.mainChartSetting.chart_name = "汇总数据计算";
            buildHtml("汇总数据计算", outTrxObj.mainChartSetting, outTrxObj.totalPointData);
            for (var i=0; i<outTrxObj.chartGridVo_list.length; i++) {
                buildHtml(i, outTrxObj.chartGridVo_list[i].chartSetting, outTrxObj.chartGridVo_list[i].pointData);
            }
        }

        function showGridData(number, chartSetting, pointDataList) {
            var summaryObj = {};

            var data = new Object();
            data.upl = chartSetting.chart_upl;
            data.usl = chartSetting.chart_usl;
            data.ucl = chartSetting.chart_ucl;
            data.target = chartSetting.chart_target;
            data.lcl = chartSetting.chart_lcl;
            data.lsl = chartSetting.chart_lsl;
            data.lpl = chartSetting.chart_lpl;
            data.cname = chartSetting.chart_name;
            data.ctitle = chartSetting.chart_dsc;
            data.cunit = chartSetting.chart_unit;
            data.chart_typ = chartSetting.chart_typ_fk;
            data.gname = chartSetting.grp_name;
            data.chart_space = chartSetting.chart_space;
            chartTyp = chartSetting.chart_typ_fk;

            data.point = new Array();

            for (var j = 0; j < pointDataList.length; j++) {
                var point = new Object();
                var chartData = pointDataList[j];

                point.inputTimestamp = chartData.input_timestamp;
                point.value = chartData.chart_value;
                point.glassId = chartData.prd_seq_id_fk;
                point.processEqptId = chartData.p_tool_id_fk;
                point.measurementEqptId = chartData.m_tool_id_fk;
                point.comment = chartData.chart_comment;
                //point.reporter = chartData.evt_usr;
                point.reporter = chartData.evt_usr == undefined ? "system":chartData.evt_usr;
                point.chart_rule1_rlt_fk = chartData.chart_rule1_rlt_fk;
                point.chart_spec_rlt_fk = chartData.chart_rule1_rlt_fk;
                point.proc_timestamp = chartData.proc_timestamp; // NO.03
                point.wo_id_fk = chartData.wo_id_fk;
                point.cus_id_fk = chartData.cus_id_fk;
                point.so_id_fk = chartData.so_id_fk;
                /*point.lot_id_fk = chartData.lot_id_fk;*/
                point.chart_rule_1_rlt = chartData.chart_rule1_rlt_fk;
                point.col_typ_fk = chartData.col_typ_fk;
                point.grp_no_fk = chartData.grp_no_fk;
                point.chart_no_fk = chartData.chart_no_fk;
                point.chart_typ_fk = chartData.chart_typ_fk;
                point.input_time_d = chartData.input_time_d;
                point.ucl = chartData.chart_ucl_fk;
                point.lcl = chartData.chart_lcl_fk;

                point = $.extend(point, chartData);
                // liufang add median chart
                if (chartTyp == "01" || chartTyp == '30') {
                    //MEAN                  //MEDIAN
                    point.rawData = pointDataList[j].rawDataList;
                    point.rawDataList = pointDataList[j].rawDataList;
                }
                data.point.push(point);
            }

            if (chartTyp == "01" || chartTyp == "10" || chartTyp == '30' || chartTyp == '40' || chartTyp == '50' || chartTyp == '60') {
                //todo 原始数据列表
                $("#rawDataDiv_"+number).empty();
                if (chartTyp === "01") {
                    fillRawDataGrd(data.point, data.usl, data.lsl, number);
                }
                //todo 管制图数据
                fillChatDataGrd(data.point, number);
            } else {
                //todo 子图点值
                fillChartDataGrdBySlaveChartData(data.point, number);
            }
            //todo 汇总数据
            summaryObj.mainChartSetting = chartSetting;
            summaryObj.mainChartPointArr = data.point;
            fillSummaryDataGrd(summaryObj, number);
        }

        function fillSummaryDataGrd(summaryObj, number) {
            if (number == undefined) number = "";

            var ca, cp, cpu, cpl, cpk, pp, ppk, mainTarget, grade, totalSampleCnt, totalGroupCnt, rawDataCnt;
            var str, bodyStr = "";
            var totalSampleValue, totalMainChartValue, totalSlaveValue, averageMainChartValue, averageSlaveChartValue;
            var sigma, mainUsl, mainLsl, mainUcl, mainLcl, slaveUcl, slaveLcl;
            var mainPoint, i, j, raw, slavePoint;
            var mainChartSetting = summaryObj.mainChartSetting, slaveChartSetting = summaryObj.slaveChartSetting;
            var mainChartPointArr = summaryObj.mainChartPointArr, slaveChartPointArr = summaryObj.slaveChartPointArr;
            var pointCnt = mainChartPointArr.length, slavePointCnt;

            if (mainChartSetting.chart_typ_fk === "40"
                || mainChartSetting.chart_typ_fk === "50"
                || mainChartSetting.chart_typ_fk === "60"
                || mainChartSetting.chart_typ_fk === "10"
                || mainChartSetting.chart_typ_fk === "01") {
                slavePointCnt = 0;
                if (!mainChartSetting || !mainChartPointArr) {
                    return false;
                }
                slaveUcl = 0;
                slaveLcl = 0;

            } else {
                if (!mainChartSetting || !slaveChartSetting || !mainChartPointArr
                    || !slaveChartPointArr) {
                    return false;
                }
                slavePointCnt = slaveChartPointArr.length;
                slaveUcl = slaveChartSetting.chart_ucl;
                slaveLcl = slaveChartSetting.chart_lcl;
            }

            // 总样本数
            totalSampleCnt = pointCnt;

            mainUsl = mainChartSetting.chart_usl;
            mainLsl = mainChartSetting.chart_lsl;
            if (typeof (mainChartSetting.chart_ucl) == "undefined") {
                if (mainChartPointArr.length > 25 && mainChartSetting.chart_typ_fk == '01') {
                    mainUcl = mainChartPointArr[mainChartPointArr.length - 1].chart_ucl_fk.toFixed(2);
                }
            } else {
                mainUcl = mainChartSetting.chart_ucl;
            }

            if (typeof (mainChartSetting.chart_lcl) == "undefined") {
                if (mainChartPointArr.length > 25 && mainChartSetting.chart_typ_fk == '01') {
                    mainLcl = mainChartPointArr[mainChartPointArr.length - 1].chart_lcl_fk.toFixed(2);
                }
            } else {
                mainLcl = mainChartSetting.chart_lcl;
            }

            mainTarget = mainChartSetting.chart_target;

            totalSampleValue = 0;
            totalMainChartValue = 0;
            totalSlaveValue = 0;

            for (i = 0; i < pointCnt; i++) {
                mainPoint = mainChartPointArr[i];
                var chartTyp = mainChartSetting.chart_typ_fk;
                if (chartTyp === "01" || chartTyp === "30") {
                    rawArr = mainPoint.rawData;
                    // 组内数
                    rawDataCnt = $.isArray(rawArr) ? rawArr.length : 0;
                    if (rawArr && rawDataCnt > 0) {
                        for (j = 0; j < rawDataCnt; j++) {
                            raw = rawArr[j];
                            // 总主图值：所有mean点加总
                            totalMainChartValue += raw.prd_raw_value;
                        }
                    }

                }

                // 总样本值
                totalSampleValue += mainPoint.value;

            }

            if (slavePointCnt != 0) {
                // 总子图值 : 子图所有点加总
                for (i = 0; i < slaveChartPointArr.length; i++) {
                    slavePoint = slaveChartPointArr[i];
                    totalSlaveValue += slavePoint.value;
                }

            } else {
                totalSlaveValue = 0;
            }
            // 总组数 = 总样本数 * 组内数
            totalGroupCnt = totalSampleCnt * rawDataCnt;

            // 主图均值 = 总样本值/总样本数
            averageMainChartValue = totalSampleValue / totalSampleCnt;

            // 子图均值 ＝ 总子图值/样本总数
            averageSlaveChartValue = totalSlaveValue / totalSampleCnt;

            // ca = (实际均值 - 中心值) / (t/2) --- t = (usl - lsl)
            var t = mainUsl - mainLsl;
            ca = Math.abs((averageMainChartValue - mainTarget) / (t / 2));
            //单边
            if (mainUsl == null || mainLsl == null) {
                ca = 0;
            }

            // sigma 标准差
            var avgSum = 0;
            var mean = averageMainChartValue;
            for (i = 0; i < pointCnt; i++) {
                mainPoint = mainChartPointArr[i];
                avgSum += (mainPoint.value - mean) * (mainPoint.value - mean);
            }
            sigma = Math.sqrt(avgSum / (pointCnt - 1));
            cp = t / (6 * sigma);
            //单边
            if (mainUsl == null && mainLsl != null) {
                cp = (mean - mainLsl) / (3 * sigma);
            } else if (mainUsl != null && mainLsl == null) {
                cp = (mainUsl - mean) / (3 * sigma);
            }

            cpl = (mean - mainLsl) / (6 * sigma);
            cpu = (mainUsl - mean) / (6 * sigma);

            // cpk = cpl > cpu ? cpu : cpl;
            cpk = (1 - Math.abs(ca)) * cp;
            //单边
            if (mainUsl == null || mainLsl == null) {
                cpk = cp;
            }

            // 计算ppk
            // 计算 sigma_ppk
            var sigma_ppk;
            if (mainChartSetting.chart_typ_fk == "01") {
                var tmpSumSum_ppk = 0;
                for (i = 0; i < pointCnt; i++) {
                    point = mainChartPointArr[i];
                    var tmpSum_ppk = 0;
                    if (point.rawData && $.isArray(point.rawData)) {

                        for (j = 0; j < point.rawData.length; j++) {
                            raw = point.rawData[j];
                            var rawValue = raw.prd_raw_value;
                            tmpSum_ppk = tmpSum_ppk
                                + Math.pow((rawValue - mean), 2);
                        }

                        tmpSumSum_ppk = tmpSumSum_ppk + tmpSum_ppk;
                    }
                }
                sigma_ppk = Math.sqrt(tmpSumSum_ppk / (pointCnt * rawDataCnt - 1));

                // 计算 pp
                if (mainUsl != null && mainLsl != null) {
                    pp = (mainUsl - mainLsl) / (sigma_ppk * 6);
                } else if (mainUsl != null && mainLsl == null) {
                    pp = (mainUsl - mean) / (sigma_ppk * 3);
                } else if (mainUsl == null && mainLsl != null) {
                    pp = (mean - mainLsl) / (sigma_ppk * 3);
                }
                // 计算 ppk
                if (mainUsl != null && mainLsl != null) {
                    ppk = (1 - Math.abs(ca)) * pp;
                } else {
                    ppk = pp;
                }

            } else {
                sigma_ppk = sigma;
                ppk = cpk;
            }

            if (cpk >= 1.67) {
                grade = "A+";
            } else if (cpk >= 1.33) {
                grade = "A";
            } else if (cpk >= 1.00) {
                grade = "B";
            } else if (cpk >= 0.67) {
                grade = "C";
            } else {
                grade = "D";
            }

            //bootstrap 汇总数据表格
            bodyStr = '<div class="table-responsive">';
            bodyStr += '<table id="summaryTbl_'+number+'" class="table table-striped">';
            bodyStr += ' <caption style="color: mediumblue;font-weight: bold;font-size: 15px;">汇总数据:</caption>';
            bodyStr += '<tbody> ' +
                ' <tr>' +
                '<th>CA</th>' +
                ' <th>CP</th>' +
                ' <th>CPU</th>' +
                ' <th>CPL</th>' +
                ' <th>CPK</th>' +
                ' <th>PP</th>' +
                ' <th>PPK</th>' +
                ' <th>GRADE</th>' +
                '</tr> ' +
                '<tr> ' +
                '<td>' + formatDouble(ca) + '</td> ' +
                '<td>' + formatDouble(cp) + '</td> ' +
                '<td>' + formatDouble(cpu) + '</td> ' +
                '<td>' + formatDouble(cpl) + '</td> ' +
                '<td>' + formatDouble(cpk) + '</td> ' +
                '<td>' + formatDouble(pp) + '</td> ' +
                '<td>' + formatDouble(ppk) + '</td> ' +
                '<td>' + grade + '</td> ' +
                '</tr> ' +
                ' <tr>' +
                '<th>总样本数</th>' +
                ' <th>总组数</th>' +
                ' <th>组内数</th>' +
                ' <th>总样本值</th>' +
                ' <th>总主图值</th>' +
                ' <th>总子图值</th>' +
                ' <th>主图均值</th>' +
                ' <th>子图均值</th>' +
                '</tr> ' +
                '<tr> ' +
                '<td>' + formatDouble(totalSampleCnt) + '</td> ' +
                '<td>' + formatDouble(totalGroupCnt) + '</td> ' +
                '<td>' + formatDouble(rawDataCnt) + '</td> ' +
                '<td>' + formatDouble(totalSampleValue) + '</td> ' +
                '<td>' + formatDouble(totalMainChartValue) + '</td> ' +
                '<td>' + formatDouble(totalSlaveValue) + '</td> ' +
                '<td>' + formatDouble(averageMainChartValue) + '</td> ' +
                '<td>' + formatDouble(averageSlaveChartValue) + '</td> ' +
                '</tr> ' +
                ' <tr>' +
                '<th>标准差</th>' +
                ' <th>主USL</th>' +
                ' <th>主LSL</th>' +
                ' <th>主UCL</th>' +
                ' <th>主LCL</th>' +
                ' <th>子UCL</th>' +
                ' <th>子LCL</th>' +
                '</tr> ' +
                '<tr> ' +
                '<td>' + formatDouble(sigma) + '</td> ' +
                '<td>' + formatDouble(mainUsl) + '</td> ' +
                '<td>' + formatDouble(mainLsl) + '</td> ' +
                '<td>' + formatDouble(mainUcl) + '</td> ' +
                '<td>' + formatDouble(mainLcl) + '</td> ' +
                '<td>' + formatDouble(slaveUcl) + '</td> ' +
                '</tr> ' +
                '</tbody>';
            bodyStr += '</table>';
            bodyStr += '</div>';
            var sumaryDataDiv = "#sumaryDataDiv_" + number;
            $(sumaryDataDiv).empty();
            $(bodyStr).appendTo(sumaryDataDiv);
        }

        function fillRawDataGrd(pointArr, usl, lsl, number) {
            if (number == undefined) number = "";

            var i, columns, rows = [], rawArr, row, point, str, pointCnt = pointArr.length;
            var str, headStr, bodyStr = "", rowStr;

            headStr = buildRawDataHeadStr(pointCnt);
            if (!headStr) {
                return false
            }

            bodyStr = buildRawDataRowStr(pointArr, usl, lsl);
            if (!bodyStr) {
                return false;
            }
            str = '<div class="table-responsive">';
            str += '<table id="rawDataTbl_' + number + '" class="table table-striped"><thead>';
            str += headStr + '</thead>';
            str += '<caption style="color: mediumblue;font-weight: bold;font-size: 15px;">原始数据:</caption>';
            str += '<tbody>' + bodyStr + '</tbody>';
            str += '</table>';
            str += '</div>';

            var rawDataDiv = "#rawDataDiv_" + number;

            $(rawDataDiv).empty();
            $(str).appendTo(rawDataDiv);
        }

        function fillChatDataGrd(pointArr, number) {
            if (number == undefined) number = "";

            var i, j, pointCnt, columns, point, rawArr, obj, raw, row1, row2, row3, rawValue, str;
            pointCnt = pointArr.length;

            var theadStr = '';
            var row0Str = "<th  style='width: 90px;'>序号</th>";
            var row1Str = "<td style='width: 90px;'>原始值求和</td>", row2Str = "<td style='width: 90px;'>主图点值</td>";
            var hasRawData = false;
            for (i = 0; i < pointCnt; i++) {
                theadStr += '<th>' + (i + 1) + '</th>';
                row0Str += '<th>' + (i + 1) + '</th>';
                point = pointArr[i];
                rawArr = point.rawData;
                if (rawArr) {
                    //默认原始值共存
                    hasRawData = true;
                    rawValue = 0;
                    for (j = 0; j < rawArr.length; j++) {
                        raw = rawArr[j];
                        rawValue = rawValue + raw.prd_raw_value;
                    }
                    row1Str += "<td>" + rawValue.toFixed(4) + "</td>";
                }
                row2Str += "<td>" + point.value.toFixed(4) + "</td>"
            }
            str = '<div class="table-responsive">';
            str += ' <table id="chartDataTbl_"' + number + ' class="table">';
            str += ' <caption style="color: mediumblue;font-weight: bold;font-size: 15px;">管制图数据:</caption>';
            '<thead><tr>' + theadStr + '</tr></thead>';
            str += "<tbody><tr>" + row0Str + "</tr>";
            if (hasRawData) {
                str += "<tr>" + row1Str + "</tr>";
            }
            str += "<tr>" + row2Str + "</tr></tbody></table>";
            str += "</div>";

            var chartDataDiv = "#chartDataDiv_" + number;

            $(chartDataDiv).empty();
            if (pointCnt <= 0) return false;
            $(str).appendTo(chartDataDiv);
        }

        function fillChartDataGrdBySlaveChartData(pointArr, number) {
            if (number == undefined) number = "";

            var i, point, row3, pointCnt;
            var str = "<tr><td>子图点值</td>";

            pointCnt = pointArr.length;

            for (i = 0; i < pointCnt; i++) {
                point = pointArr[i];
                str += "<td>" + point.value.toFixed(3) + "</td>";
            }

            str += "</tr>";

            var chartDataTbl = "#chartDataTbl_" + number;

            $(str).appendTo(chartDataTbl + " tbody");
        }

        function buildRawDataHeadStr(pointCnt) {
            var str = "<thead><th>序号</th>";
            if (pointCnt <= 0) {
                return null;
            }
            for (i = 0; i < pointCnt; i++) {
                str += "<th>" + (i + 1) + "</th>";
            }
            str += "</thead>";
            return str;
        }

        // 将一组rawData组成一行 并返回
        function buildRawDataRowStr(pointArr, usl, lsl) {
            var str = "", raw, i, j, pointCnt = pointArr.length, rawDataCnt, maxRawDataCnt;

            var rawDataCnt = 0;
            maxRawDataCnt = 0;
            if (pointCnt <= 0) {
                return false;
            }

            for (i = 0; i < pointArr.length; i++) {
                if (pointArr[i].rawData) {
                    rawDataCnt = pointArr[i].rawData.length;
                    if (rawDataCnt > maxRawDataCnt) {
                        maxRawDataCnt = rawDataCnt;
                    }
                }
            }

            if (maxRawDataCnt <= 0) {
                return false;
            }

            // add tr : prd_seq_id
            str = str + "<tr><td style='width: 90px;'>量测次数</td>";
            for (i = 0; i < pointCnt; i++) {
                var point = pointArr[i];
                if (isOOS(point.value, point.chart_typ_fk, usl, lsl)) {
                    str += "<td style ='color:red' >" + point.glassId + "</td>";
                } else {
                    str += "<td>" + point.glassId + "</td>";
                }

            }
            str = str + "</tr>";

            for (i = 0; i < maxRawDataCnt; i++) {
                str = str + "<tr><td>" + (i + 1) + "</td>";
                for (j = 0; j < pointCnt; j++) {
                    var point = pointArr[j];
                    //console.info(point);
                    var rawData = point ? point.rawData : null;
                    //console.info(rawData);

                    raw = (rawData && $.isArray(rawData) && rawData.length > i - 1)
                        ? rawData[i]
                        : null;

                    if (raw) {
                        if (isOOS(raw.prd_raw_value, pointArr[j].chart_typ_fk, usl,
                                lsl)) {
                            str += "<td style ='color:red'>" + raw.prd_raw_value
                                + "</td>";
                        } else {
                            str += "<td>" + raw.prd_raw_value + "</td>";
                        }
                    } else {
                        str += "<td></td>";
                    }
                }
                str += "</tr>";
            }

            return str;
        }

        function isOOS(pointValue, chartTyp, usl, lsl) {

            return isMainChart(chartTyp)
                && ((usl != null && pointValue > usl) || (lsl != null && pointValue < lsl));
        }

        function isMainChart(chartTyp) {
            return chartTyp == "01" || chartTyp == "10" || chartTyp == '30'
                || chartTyp == '40' || chartTyp == '50' || chartTyp == '60';
        }

        function formatDouble(dbl) {
            var strDbl = dbl + "";
            if(strDbl == "undefined" || strDbl == "NaN" || strDbl == "-Infinity"){
                strDbl = "0";
            }
            var index = strDbl.indexOf(".");
            if (index === -1) {
                return strDbl + ".000";
            }
            var strRight = strDbl.substr(index + 1);
            var strLeft = strDbl.substr(0, index);
            if (strRight.length > 3) {
                return strDbl.substr(0, index + 4);
            } else {
                return strLeft + "." + ComL2S(strRight, 3, "0")
            }
        }

        function ComL2S(data1, length, data2) {
            if (length <= 0) {
                return null;
            }
            var str = data1.toString();
            if (data1.length > length) {
                return null;
            }
            var size = str.length;
            var chazhi = length - size;
            for (var i = 0; i < chazhi; i++) {
                str = str + data2;
            }
            return str;
        }

    });
</script>
